﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;

namespace mesoBoard.Data.Repositories
{
    public class ThemeRepository : IThemeRepository
    {
        private mbEntities db;

        public ThemeRepository(mbEntities mbDataContext)
        {
            this.db = mbDataContext;
        }

        public bool ThemeExists(string ThemeName)
        {
            return db.Themes.FirstOrDefault(x => x.FolderName == ThemeName) != null;
        }

        public Theme GetTheme(int ThemeID)
        {
            return db.Themes.FirstOrDefault(x => x.ThemeID == ThemeID);
        }

        public IEnumerable<Theme> GetThemes()
        {
            return db.Themes.AsEnumerable();
        }

        public Theme GetUserTheme(int UserID)
        {
            return db.Users.FirstOrDefault(x => x.UserID == UserID).UserProfile.Theme;
        }

        public void SetDefaultTheme(int ThemeID)
        {
            db.Configs.FirstOrDefault(x => x.Name == "BoardTheme").Value = ThemeID.ToString();
            db.SaveChanges();
        }

        public Theme GetDefaultTheme()
        {
            return GetTheme(int.Parse(db.Configs.FirstOrDefault(x => x.Name == "BoardTheme").Value));
        }

        public int CreateTheme(Theme TheTheme)
        {
            db.Themes.AddObject(TheTheme);
            db.SaveChanges();
            return TheTheme.ThemeID;
        }

        public void DeleteTheme(int ThemeID)
        {
            db.Themes.DeleteObject(GetTheme(ThemeID));
            db.SaveChanges();
        }

        public void UpdateTheme(Theme TheTheme)
        {
            if (TheTheme.EntityKey == null)
                TheTheme.EntityKey = ((Theme)db.GetObjectByKey(new System.Data.EntityKey("mbEntities.Themes", "ThemeID", TheTheme.ThemeID))).EntityKey;

            db.Themes.ApplyCurrentValues(TheTheme);
            db.SaveChanges();
        }

        public void SubmitChanges()
        {
            db.SaveChanges();
        }
    }
}
